package com.uroad.jilinpda.http;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Toast;


import com.uroad.jilinpda.activity.LoginActivity;
import com.uroad.jilinpda.common.CurrApplication;
import com.uroad.jilinpda.common.GlobalData;
import com.uroad.lib.http.OkHttpUtils;
import com.uroad.lib.http.builder.PostFormBuilder;
import com.uroad.lib.http.callback.StringCallback;
import com.uroad.lib.util.log.LogUtil;
import com.uroad.lib.util.net.NetWorkUtil;
import com.uroad.lib.widget.dialog.DialogHelper;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Cookie;
import okhttp3.Headers;
import okhttp3.ResponseBody;

public class OkHttpNetWork {

    private Context mContext;
    private long oldTime = 0;
    private long curTime = 0;
    private int requestCount = 0;
    private HashMap<String, String> requestList = new HashMap<>();
    private String ticketid="";
    private String useruuid="";
    //登录状态被挤出时是否退出
    protected boolean isFinish = true;

    public OkHttpNetWork(){
    }

    public OkHttpNetWork(Context context){
        this.mContext = context;
    }

    public boolean isFinish() {
        return isFinish;
    }

    public void setFinish(boolean finish) {//在我的页面调用此方法将isFinish 设置为 false
        isFinish = finish;
    }

    /***
     *
     * 网络请求
     *
     * @param url
     *            url方法名eg."/sys/getFileVer"
     * @param params
     *            请求参数
     * @param id
     *
     */

    public void doAllUrlRequest(final String url, final HashMap<String, Object> params,
                       final String id, OkHttpNetWorkCallBack callBack) {
        if (!NetWorkUtil.checkNet(mContext)) {
            callBack.OnHttpNetWork(id);
            return;
        }
        PostFormBuilder postFormBuilder = OkHttpUtils.post();
        if (url.contains("eaaspush/device/login"))
            params.put("cookie", OkHttpUtils.getInstance().getCooki());
        if (params != null && params.size() > 0) {
            for (Map.Entry<String, Object> entry : params.entrySet()) {
                postFormBuilder.addParams(entry.getKey(), entry.getValue() + "");
            }
        }
        LogUtil.i("BaseUroadActivity", "接口:" + url + "\n" + "参数：" + params.toString());
        postFormBuilder.url(url)
                .id(id)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, String id) {
                        if (mContext instanceof Activity && !((Activity)mContext).isFinishing()) {
                            LogUtil.i("BaseUroadActivity", "接口" + id + "调用失败:" + e.toString()+"\n"+e.getMessage());
                            callBack.OnHttpFailure(id, e.getMessage());
                        }else if(!(mContext instanceof Activity)){
                            LogUtil.i("BaseUroadActivity", "接口" + id + "调用失败:" + e.toString()+"\n"+e.getMessage());
                            callBack.OnHttpFailure(id, e.getMessage());
                        }
                    }

                    @Override
                    public void onResponse(String response, String id) {
                        try {
                            LogUtil.i("BaseUroadActivity", "接口：" + id + "\n返回：" + response);
                            if (mContext instanceof Activity && !((Activity)mContext).isFinishing()) {
                                callBack.OnHttpTaskComplete(response, id);
                            }else if(!(mContext instanceof Activity)){
                                callBack.OnHttpTaskComplete(response, id);
                            }
                        } catch (Exception e) {
                            LogUtil.i("BaseUroadActivity", "接口" + id + "执行异常:" + e.getMessage());
                            e.printStackTrace();
                            if (mContext instanceof Activity && !((Activity)mContext).isFinishing()) {
                                callBack.OnHttpFailure(id, e.getMessage());
                            }else if(!(mContext instanceof Activity)){
                                callBack.OnHttpFailure(id, e.getMessage());
                            }
                        }
                    }
                });
    }





    /***
     *
     * 网络请求
     *
     * @param url
     *            url方法名eg."/sys/getFileVer"
     * @param params
     *            请求参数
     * @param type
     *
     */
   /* @SuppressLint("StaticFieldLeak") //先发现安卓5.0版本一下不支持假证书的Https请求
    public void doAllUrlRequest(final String url, final RequestParams params,
                                final String type, OkHttpAndLoadAotCallBack callBack) {
        if (mContext != null&&!NetWorkUtil.checkNet(mContext)) {
            callBack.OnHttpTaskResult(-2,"", type);//0 成功  -1 请求失败  -2 无网络
            return;
        }
        long starttime = System.currentTimeMillis();
        curTime = starttime;
        LogUtils.i("time statistics activity request start:" + (curTime - oldTime) + "\n" + url);
        LogUtils.i("接口：" + url + "\n请求参数：" + params.toString());
        if (AppUtils.isDebug()) {
            requestCount++;
            requestList.put(url + requestCount, "接口：" + url + "\n请求参数：" + params.toString());
        }
        if (CurrApplication.userLoginer != null){
            ticketid = CurrApplication.userLoginer.getTicketid();
            useruuid = CurrApplication.userLoginer.getUseruuid();
        }
//        ticketid = (String) SPUtils.get(mContext, GlobalData.sp_ticketid, "");
//        useruuid = (String) SPUtils.get(mContext, GlobalData.sp_useruuid, "");

        List<BasicNameValuePair> paramsList = params.getParamsList();
        PostFormBuilder builder = OkHttpUtils.post();
        builder.url(url).id(type);
        builder.addParams("ticketid",ticketid);
        builder.addParams("useruuid",useruuid);
        builder.addParams("deviceuuid", CurrApplication.getInstance().deviceuuid);
        for (BasicNameValuePair pair : paramsList) {
            builder.addParams(pair.getName(), pair.getValue());
        }
        builder.build().execute(new StringCallback() {

            @Override
            public void onResponse(String response, String id) {
                long endtime = System.currentTimeMillis();
                curTime = endtime;
                LogUtils.i("time statistics activity request end:" + (curTime - oldTime) + "\n" + url);
                LogUtils.i("接口：" + url + "\n调用时间:" + (endtime - starttime));
                if (AppUtils.isDebug()) {
                    requestCount++;
                    requestList.put(url + requestCount, "接口：" + url + "\n调用时间:" + (endtime - starttime) + "\n返回数据：" + response);
                }
                if (response == null) {
//                    callBack.OnHttpFailure(type, "系统繁忙，请稍后重试！");
                    callBack.OnHttpTaskResult(-1,"系统繁忙，请稍后重试！", type);
                } else if (response.toString().contains("certificateError")) {
//                    callBack.OnHttpFailure(type, "certificateError");
                    callBack.OnHttpTaskResult(-1,"certificateError", type);
                } else {
                    JSONObject result = null;
                    try {
                        result = new JSONObject(response);
                        LogUtils.i("接口：" + url + "\n返回数据：" + response);
//                    callBack.OnHttpTaskComplete(result, type);
//                    callBack.OnHttpTaskComplete(result.toString(), type);
                        callBack.OnHttpTaskResult(0,result.toString(), type);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void onError(Call call, Exception e, String id) {
//                callBack.OnHttpFailure(type, e.getMessage());
                callBack.OnHttpTaskResult(-1, e.getMessage(), type);
            }

        });
    }*/

}
